package org.netty.framework.core.concurrent;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class NettyServerThreadFactory implements ThreadFactory {

	private final AtomicInteger nextId = new AtomicInteger();
	private final String prefix;
	private final boolean daemon;
	private final int priority;
	protected final ThreadGroup threadGroup;

	public NettyServerThreadFactory(String poolName) {
		this(poolName, false, Thread.NORM_PRIORITY);
	}

	public NettyServerThreadFactory(String poolName, boolean daemon, int priority, ThreadGroup threadGroup) {
		if (poolName == null) {
			throw new NullPointerException("poolName");
		}
		if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) {
			throw new IllegalArgumentException(
					"priority: " + priority + " (expected: Thread.MIN_PRIORITY <= priority <= Thread.MAX_PRIORITY)");
		}

		prefix = poolName + '-';
		this.daemon = daemon;
		this.priority = priority;
		this.threadGroup = threadGroup;
	}

	public NettyServerThreadFactory(String poolName, boolean daemon, int priority) {
		this(poolName, daemon, priority, System.getSecurityManager() == null ? Thread.currentThread().getThreadGroup()
				: System.getSecurityManager().getThreadGroup());
	}

	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r, prefix + nextId.incrementAndGet());
		try {
			if (t.isDaemon() != daemon) {
				t.setDaemon(daemon);
			}

			if (t.getPriority() != priority) {
				t.setPriority(priority);
			}
		} catch (Exception ignored) {
			// Doesn't matter even if failed to set.
		}
		return t;
	}

}
